package Recipient;
use Salutation;
use Utils::Strings;

sub new
{
    my ($class, $db_name)	= @_;		
    my $self		= {};
    $self->{db_name}	= $db_name;

    $self->{id}		= 0;
    $self->{active}	= "0,1";
    $self->{paginate}	= 0;
    $self->{search_str}	= "";
    $self->{group_id}	= 0;
    $self->{salutation}	= '';
    $self->{salutation_id}	= 0;
    $self->{salutation_include}	= '';
    $self->{f_name_include}	= '';
    $self->{l_name_include}	= '';
    $self->{random_key}	= '';
    $self->{type_id}	= 1;
    $self->{realm_id}	= 0;

    $self->{greeting}	= "";

    bless $self, 'Recipient';
    return $self;
}

sub newFromDBById
{
    my ($class, $recipient_id)	= @_;
    my $self = {};

    my $stmt = "SELECT  f_name, l_name, active, email_addr, signup_date, signup_ip, 
                        salutation, salutation_id, salutation_include, f_name_include, l_name_include, 
                        random_key, company_name, company_name_short, type_id, realm_id
                FROM 	recipients
                WHERE 	id = $recipient_id";

    my $kit_db      = new KIT_DB();
    my $hashref	= $kit_db->GetSingleRow($stmt) || die $!;

    $self->{recipient_id}   =	$recipient_id;
    $self->{f_name}         =	$hashref->{f_name};
    $self->{l_name}         =	$hashref->{l_name};
    $self->{email_addr}	    =	$hashref->{email_addr};
    $self->{random_key}	    =	$hashref->{random_key};
    $self->{active}	    =	$hashref->{active};
    $self->{type_id}	    =	$hashref->{type_id};

    $self->{salutation}     =   $hashref->{salutation};
    $self->{salutation_id}	= $hashref->{salutation_id};
    $self->{salutation_include} = $hashref->{salutation_include};
    $self->{f_name_include}	= $hashref->{f_name_include};
    $self->{l_name_include}	= $hashref->{l_name_include};

    $self->{company_name}	= $hashref->{company_name};
    $self->{company_name_short}	= $hashref->{company_name_short};
    $self->{realm_id}   =   $hashref->{realm_id};

    bless $self, 'Recipient';
    return $self;
}

sub newFromDBByKey
{
    my ($class, $random_key)	= @_;

    my $self	= {};

    my $stmt    =   "SELECT f_name, l_name, active, email_addr, signup_date, signup_ip, 
                            salutation, salutation_include, f_name_include, l_name_include, id, 
                            company_name, company_name_short, type_id,realm_id, salutation_id
                     FROM   recipients
                     WHERE  random_key = '$random_key'";

    my $kit_db      = new KIT_DB();
    my $hashref	= $kit_db->GetSingleRow($stmt);

    $self->{f_name}         = $hashref->{f_name};
    $self->{l_name}         = $hashref->{l_name};
    $self->{email_addr}     = $hashref->{email_addr};
    $self->{recipient_id}   = $hashref->{id};
    $self->{active}         = $hashref->{active};
    $self->{company_name}   = $hashref->{company_name};
    $self->{company_name_short} = $hashref->{company_name_short};
    $self->{type_id}        = $hashref->{type_id};

    $self->{salutation}     = $hashref->{salutation};
    $self->{salutation_include} = $hashref->{salutation_include};
    $self->{salutation_id}  = $hashref->{salutation_id};
    $self->{f_name_include} = $hashref->{f_name_include};
    $self->{l_name_include} = $hashref->{l_name_include};
    $self->{realm_id}       = $hashref->{realm_id};

    bless $self, 'Recipient';
    return $self;
}

sub GetRecipientIdFromRandomKey
{
    my ($self, $random_key)	= @_;

    my $stmt       = "SELECT id as ret_val FROM tbl_recipients WHERE random_key = '" . $random_key . "'";
    my $kit_db     = new KIT_DB($self->{db_name});

    return $kit_db->GetSingleValue($stmt);
}

#	-- Returns array of recipients given a group_id
sub GetRecipients
{
    my ($self)	= @_;

    my @recipients          = ();
    my $search_where_sql    = '';
    my $active_where_sql    = '';
    my $limit_sql           = '';

    my $kit_db              = new KIT_DB();

#	-- For availing the $logger
		my $utils		= new Utils();
		my $logger	= $utils->init_logger();

		$logger->debug("Limit = ", $self->{record_limits});

#	-- Not a great idea, but fix for anywhere we are forgetting to get the $self->record_limits variable
#		$self->{record_limits}	= 10;
		
    $active_where_sql   = "AND RG.active IN (" . $self->{active} . ")";
    $limit_sql          = "LIMIT " . $self->{record_limits} if ($self->{paginate} == 1);
    $search_where_sql   = $self->{search_str} if (length($self->{search_str})> 0);

    my $stmt = "SELECT R.id, R.f_name, R.l_name, R.email_addr, R.signup_date, RG.active, 
                       R.salutation_include, R.f_name_include, R.l_name_include, R.salutation,
                       R.random_key, R.company_name, R.company_name_short, R.type_id, RG.id,
                       R.salutation_id
                FROM recipients AS R, recipients_groups AS RG, groups AS G
                WHERE   1
                $search_where_sql
                $active_where_sql
                AND     group_id = $self->{group_id}
                AND     RG.group_id = G.id
                AND     RG.recipient_id = R.id
                AND     R.type_id = $self->{type_id}
                AND     R.realm_id = $self->{realm_id}
                ORDER BY R.id DESC, R.signup_date DESC $limit_sql;";

		$logger->debug($stmt);
    my @rows	= $kit_db->GetMultipleRows($stmt);
    my $count	= 0;

    my $salutation  = new Salutation();
       $salutation->{realm_id}  = $self->{realm_id};

    my @SALUTATIONS = $salutation->get_all_salutations();

    my $utils       = new Utils();

    #   -- We use the Html::Template to create the <select> box
    my $htmlTmpl    = $utils->init_template('Settings/salutations_select.html');
       $htmlTmpl->param('SALUTATIONS' => [@SALUTATIONS]);

    foreach my $row (@rows) 
    {
        #  -- JS for editing a record, AJAX code printed once per loop iteration
        my $edit_ajax	= new CGI::Ajax( EditRecipient => 'addr.cgi' );

        my $salute_type	=  $row->[9];

        if ($salute_type) {
            $salute_type	=~ s/\s/_/g;
            $salute_type	=~ s/\.//g;

            $salute_type	= 'salutation_' . $salute_type;
        }

        my ($current_salutation_id, $current_salutation, $salutation) = (0, '', '');
           $current_salutation_id   = $row->[15];

        if ($current_salutation_id > 0) {
            $salutation              = newFromDB Salutation($current_salutation_id);
            $current_salutation      = $salutation->{salutation};
        }

        $htmlTmpl->param('recipient_id', $row->[0]);
        $htmlTmpl->param('current_salutation_id', $row->[15]);
        $htmlTmpl->param('current_salutation', $current_salutation);

        my $greeting    = $self->get_greeting($row->[0]);

        my $salutations_html    = $htmlTmpl->output();

        my %recipient =
        (
            recipient_id        => $row->[0],
            f_name	        => $row->[1],
            l_name              => $row->[2],
            email_addr          => $row->[3],
            ISACTIVE            => $row->[5],
            salute_type         => 1,
            SALUTATION_INCLUDE  => $row->[6],
            F_NAME_INCLUDE      => $row->[7],
            L_NAME_INCLUDE      => $row->[8],
            edit_ajax           => $edit_ajax,
            recipient_key       => $row->[10],
            salutation          => $row->[9],
            company_name        => $row->[11],
            company_name_short  => $row->[12],
            type_id             => $row->[13],
            recipient_group_id  => $row->[14],
            salutations_html    => $salutations_html,
            current_salutation  => $current_salutation,
            index               => ++$count,
            salutation_id       => $current_salutation_id,
            greeting            => $greeting,
        );
        push @recipients, \%recipient;
    }

    return @recipients;
}

sub UpdateRecipient
{
    my ($self) = @_;

    # use Utils;
    my $utils   = new Utils();
    my $kit_db  = new KIT_DB();

    my $salutation	= $utils->sanitizeApostrophe(trim($self->{salutation}));
    my $salutation_include  = trim($self->{salutation_include});
    my $salutation_id       = $self->{salutation_id};

    my $recipient_id        = $utils->sanitizeApostrophe(trim($self->{recipient_id}));

    my $f_name          = $utils->sanitizeApostrophe(trim($self->{f_name}));
    my $l_name          = $utils->sanitizeApostrophe(trim($self->{l_name}));
    my $f_name_include  = trim($self->{f_name_include});
    my $l_name_include  = trim($self->{l_name_include});
    my $email_addr          = trim($self->{email_addr});

    my $company_name        = $utils->sanitizeApostrophe(trim($self->{company_name}));
    my $company_name_short  = $utils->sanitizeApostrophe(trim($self->{company_name_short}));

    my $stmt;
        $stmt   = " update recipients
                    set 
                    f_name             = '$f_name',
                    f_name_include     = $f_name_include,
                    l_name             = '$l_name',
                    l_name_include     = $l_name_include,
                    email_addr         = '$email_addr',
                    salutation_include = $salutation_include,
                    company_name       = '$company_name',
                    company_name_short = '$company_name_short',
                    type_id            = $self->{type_id},
                    salutation_id      = $salutation_id
                    where
                    id = $recipient_id";
#     print $stmt; exit;
    return $kit_db->Update($stmt);
}

sub InsertRecipient
{
    my ($self) 	= @_;
    my $rand_key	= Utils->GenerateRandomKey(8);

    my $active = 0;
        $active = 1 if ($self->{active} eq 'on' || $self->{active} == 1);

    my $utils   = new Utils();
    my $kit_db  = new KIT_DB();

    my $f_name          = $utils->sanitizeApostrophe($self->{f_name});
    my $l_name          = $utils->sanitizeApostrophe($self->{l_name});
    my $company_name    = $utils->sanitizeApostrophe($self->{company_name});
    my $company_name_short  = $utils->sanitizeApostrophe($self->{company_name_short});

    my $stmt;
        $stmt 	= "INSERT INTO recipients
                   (f_name, l_name, email_addr, active, random_key, type_id, 
                    company_name, company_name_short, realm_id, salutation_id) 
                   VALUES 
                   ('$f_name', '$l_name', \"$self->{email_addr}\", $active, '$rand_key', 
                    $self->{type_id}, '$company_name', '$company_name_short', 
                    $self->{realm_id}, $self->{salutation_id})";
    # print $stmt;exit;
    return $kit_db->Insert($stmt);
}

sub GetTypeDesc
{
    my $self  	= shift;
    my $type_id	= shift || $self->{type_id};
    my $kit_db  = new KIT_DB();

    my $stmt	= "SELECT type_desc as ret_val FROM recipient_types WHERE id = " . $type_id;
    return $kit_db->GetSingleValue($stmt);
}


sub SetActiveInGroup
{
    my $self	= shift;
    my $active_bit	= shift;

    my $kit_db  = new KIT_DB();
    my $stmt	= "UPDATE recipients_groups SET active = $active_bit WHERE recipient_id = $self->{recipient_id} AND group_id = $self->{group_id};";

    # 	print $stmt; exit;
    return $kit_db->Update($stmt);
}

#	-- Just checks if there is such an email in the whole db.  NOT VERY USEFUL
sub CheckEmailExists
{
    my $self        = shift;
    my $email_addr  = shift || $self->{email_addr};
    
    my $kit_db      = new KIT_DB();
    my $stmt        = "SELECT count(*) AS ret_val FROM recipients WHERE email_addr = '" . $email_addr . "' AND realm_id = " . $self->{realm_id};

#     print $stmt;
    return  $kit_db->GetSingleValue($stmt);
}

sub groups_email_exists
{
    my ($self, $email_addr)  = @_;
    
    
}

#	-- Checks per group if an email exists.  Use for SB csv imports etc
sub CheckEmailExistsByGroup
{
    my $self	= shift;
    my $email_addr	= shift || $self->{email_addr};

    my $kit_db  = new KIT_DB();
    my $stmt	= "SELECT count(*) AS ret_val 
                   FROM   recipients_groups AS RG, recipients AS R
                   WHERE  email_addr = \"$self->{email_addr}\"
                   AND	  RG.recipient_id = R.id
                   AND	  RG.group_id = " . $self->{group_id} . " AND realm_id = " . $self->{realm_id};

    return  $kit_db->GetSingleValue($stmt);
}

sub GetActiveCount
{
    my $self	= shift;
    my $kit_db  = new KIT_DB();

    my $stmt	= "SELECT count(*) AS ret_val 
                    FROM   recipients_groups AS RG, recipients AS R
                    WHERE  group_id = $self->{group_id} 
                    AND    RG.active = 1 
                    AND    R.type_id = $self->{type_id}
                    AND	  RG.recipient_id = R.id";

    return $kit_db->GetSingleValue($stmt);
}

sub GetInActiveCount
{
    my $self	= shift;
    my $stmt	= "SELECT count(*) AS ret_val 
                   FROM   recipients_groups AS RG, recipients AS R
                   WHERE  group_id = $self->{group_id} 
                   AND    RG.active = 0 
                   AND    R.type_id = $self->{type_id}
                   AND	  RG.recipient_id = R.id";

    my $kit_db  = new KIT_DB();
    return $kit_db->GetSingleValue($stmt);
}

sub GetTotalCount
{
    my $self	= shift;
    my $stmt	= "SELECT count(*) AS ret_val 
                   FROM   recipients_groups AS RG, recipients AS R
                   WHERE  group_id = $self->{group_id} 
                   AND    R.type_id = $self->{type_id}
                   AND	  RG.recipient_id = R.id";

    my $kit_db  = new KIT_DB();
    return $kit_db->GetSingleValue($stmt);
}

=pod
Gets greeting of the recipient based on settings provided on addr.cgi

There is a redundant version of this method in sendnl*.pl, which should eventually
be deprecated
=cut
sub get_greeting
{
    my $self            = shift;
    my $recipient_id    = shift || $self->{'recipient_id'};

#     my $log = Log::Log4perl->get_logger("Recipient");
#        $log->debug("Debug message");
#        $log->info("Info message");
#        $log->error("Error message");

    my $salutation;
    my $greeting    = '';

    # printf "f_name= %s, fname_include = %s", $self->{f_name}, $self->{'f_name_include'};
    my $stmt    = "SELECT f_name, l_name, f_name_include, l_name_include, salutation_id, salutation_include FROM recipients WHERE id = $recipient_id";

    my $kit_db  = new KIT_DB();
    my $row_ref     = $kit_db->GetSingleRow($stmt);

#     printf ("rcpt id = %d, sal_id = %d", $recipient_id, $row_ref->{salutation_id});

    if ( ($row_ref->{salutation_id} > 0) && ($row_ref->{'salutation_include'} > 0) )
    {
        use Salutation;
        $salutation  = newFromDB Salutation($row_ref->{salutation_id});
        $greeting    = $salutation->{'salutation'} . " ";
    }

    $greeting    .= trim($row_ref->{'f_name'}) . " "
        if ($row_ref->{'f_name'} && $row_ref->{'f_name_include'} > 0);

    $greeting    .= trim($row_ref->{'l_name'})
        if ($row_ref->{'l_name'} && $row_ref->{'l_name_include'} > 0);

    $self->{greeting}   = trim($greeting);

#     printf ("greeting = %s<br>", $greeting);

    return $greeting;
#     return trim($greeting);
}

#   -- helper function.  Can't get this to work in Utils
sub trim() 
{
#     my $self    = shift;
    my $string  = shift;
       $string  =~ s/^\s+// if defined $string;
       $string  =~ s/\s+$// if defined $string;

    return $string;
}
1;